#include<iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include<unordered_map>
#include<vector>
#include"log.hpp"
#include"socket.hpp"
#include"protocol.hpp"
#include"http.hpp"

class TcpServer{
    public:
        TcpServer(uint16_t port):_port(port),_socket(port){
            _socket.Bind(_port);
        }
        void Start(){
            _socket.Listen();
            InetAddr client_addr;
            TcpSocket* clientfd=_socket.Accept(&client_addr);
            std::string meg;
            while(true){
                if(clientfd==nullptr){
                    continue;
                }
                int n=clientfd->Recv(meg);
                if(n==-1){
                    return;
                }
                else if(n==0){
                    delete clientfd;
                    break;
                }
                else{
                    _protocol.AddMessage(meg);
                    if(meg=="||"){
                        continue;
                    }
                    std::cout<<"接收到消息: "<<meg<<" 来自 "<<client_addr.PrintDebug()<<std::endl;
                    _protocol.Deserialization();
                    meg=_protocol.Response();
                    std::cout<<"反序列化后: "<<meg<<std::endl;
                    if(meg!=""){
                        clientfd->Send(meg);
                    }
                    //TODO:处理消息
                }
            }
        }
    private:
        Http _protocol;
        TcpSocket _socket;
        uint16_t _port;
        std::vector<int> _clients;
};